package com.yxq.mdt.app.modules.personal.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.modules.adapter.UploadImageListAdapter;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.order.bean.EventOrderMsg;
import com.yxq.mdt.app.modules.order.bean.ExpressBean;
import com.yxq.mdt.app.modules.order.bean.OrderConfirmBean;
import com.yxq.mdt.app.modules.order.bean.OrderDetailBean;
import com.yxq.mdt.app.modules.order.bean.OrderListBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultBalanceBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultWxBean;
import com.yxq.mdt.app.modules.order.bean.OrderRefundPreviewBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitResult;
import com.yxq.mdt.app.modules.order.bean.UploadImageResultBean;
import com.yxq.mdt.app.modules.order.model.OrderModel;
import com.yxq.mdt.app.modules.order.prestener.IOrderContract;
import com.yxq.mdt.app.modules.order.prestener.OrderPresenter;
import com.yxq.mdt.app.modules.order.ui.adapter.OrderRefundPreviewGoodsListAdapter;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GlideEngine;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author L
 * @time 2019-11-06
 * @describe 申请售后
 */
public class MainPersonalOrderAfterAc extends BaseActivity<OrderPresenter> implements IOrderContract.View {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    final String[] CHANNELS = new String[]{"退款退货", "换货"};
    List<String> mDataList = Arrays.asList(CHANNELS);
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.et_msg)
    EditText etMsg;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.image_recycler_view)
    RecyclerView imageRecyclerView;
    UploadImageListAdapter uploadImageListAdapter;
    List<UploadImageBean> uploadImageBeanList;
    int type = 1;//类型（1退货 2换货）
    @BindView(R.id.return_layout_return)
    LinearLayout returnLayoutReturn;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main_personal_order_after;
    }

    @Override
    public void initView() {
        mPresenter = new OrderPresenter(this, new OrderModel());
        FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
        final CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new SimplePagerTitleView(context);

                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_font_black));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_font_red));
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mFragmentContainerHelper.handlePageSelected(index);
                        type = index + 1;
                        switchView(type);
                    }
                });

                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                //设置宽度
                indicator.setLineWidth(SizeUtils.dp2px(30));
                //设置高度
                indicator.setLineHeight(SizeUtils.dp2px(2));
                //设置颜色
                indicator.setColors(getResources().getColor(R.color.colorPrimary));
                //设置圆角
                indicator.setRoundRadius(5);
                //设置模式
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                return indicator;
            }
        });
        commonNavigator.setAdjustMode(true);
        magicIndicator.setNavigator(commonNavigator);
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator);
        //初始化图片上传控件
        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        uploadImageBeanList = new ArrayList<>();
        uploadImageBeanList.add(new UploadImageBean());
        uploadImageListAdapter = new UploadImageListAdapter(uploadImageBeanList);
        imageRecyclerView.setAdapter(uploadImageListAdapter);
        uploadImageListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (uploadImageListAdapter.getItem(position).getItemType() == -1) {
                    selectImages();
                }else{
                    //预览网络图片
                    if (uploadImageListAdapter.getData() != null && uploadImageListAdapter.getData().size() > 0) {
                        Intent intent = new Intent(mActivity, PictureActivity.class);
                        intent.putExtra("position", position);
                        ArrayList<String> images = new ArrayList<>();
                        for (UploadImageBean uploadImageBean : uploadImageListAdapter.getData()) {
                            if (uploadImageBean.getItemType() != -1) {
                                images.add(uploadImageBean.getPath());
                            }
                        }
                        intent.putExtra("images", images);
                        startActivity(intent);
                    }
                }
            }
        });
        uploadImageListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<UploadImageBean> uploadImageBeanList = uploadImageListAdapter.getData();
                if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                    uploadImageBeanList.remove(position);
                    //第一张不是添加图片，添加按钮
                    List<UploadImageBean> temp = new ArrayList<>();
                    temp.addAll(uploadImageBeanList);
                    temp.add(new UploadImageBean());
                    uploadImageListAdapter.setNewData(temp);
                } else {
                    uploadImageListAdapter.remove(position);
                }
            }
        });
    }

    /**
     * 切换换货与退货界面
     *
     * @param type
     */
    private void switchView(int type) {
        switch (type) {
            case 1://退款
                tvHint.setText("退款原因");
                etMsg.setHint("请输入退款原因");
                returnLayoutReturn.setVisibility(View.VISIBLE);
                break;
            case 2://换货
                tvHint.setText("换货原因");
                etMsg.setHint("请输入换货原因");
                returnLayoutReturn.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        OrderModel.refundPreview(getIntent().getStringExtra("orderId"), new ApiModel.CommonCallback<OrderRefundPreviewBean>() {
            @Override
            public void onSuccess(OrderRefundPreviewBean orderRefundPreviewBean) {
                bindUI(orderRefundPreviewBean);
                //设置退货价格
                tvPrice.setText(String.format("￥%.2f", orderRefundPreviewBean.getMax_refund_price()));
            }

            @Override
            public void onError(String errMsg) {
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 填充数据到界面
     *
     * @param orderDetailBean
     */
    private void bindUI(OrderRefundPreviewBean orderDetailBean) {
        List<OrderRefundPreviewBean> data = new ArrayList<>();
        data.add(orderDetailBean);
        //订单信息
        //购买的商品列表
        OrderRefundPreviewGoodsListAdapter orderDetailGoodsListAdapter = new OrderRefundPreviewGoodsListAdapter(R.layout.layout_order_return_goods_item_layout, data);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(orderDetailGoodsListAdapter);
        orderDetailGoodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
            //跳转商品详情
            Bundle bundle = new Bundle();
            bundle.putString("id", orderDetailGoodsListAdapter.getItem(position).getGoods_id() + "");
            IntentHelper.arouterUri(RouteTable.ROUTER_ACTIVITY_GOODS_DETAIL, bundle);
        });
    }

    @Override
    public void onLoadSuccess(OrderConfirmBean orderConfirmBean) {

    }

    @Override
    public void onLoadFailed(String err) {

    }

    @Override
    public void onLoadListSuccess(OrderListBean orderListBean) {

    }

    @Override
    public void onLoadListFailed(String err) {

    }

    @Override
    public void onSubmitSuccess(OrderSubmitResult orderSubmitResult) {

    }

    @Override
    public void onSubmitFailed(String err) {

    }

    @Override
    public void onPayBalanceSuccess(OrderPayResultBalanceBean orderPayResultBalanceBean) {

    }

    @Override
    public void onPayBalanceFailed(String err) {

    }

    @Override
    public void onPayWxSuccess(OrderPayResultWxBean orderPayResultWxBean) {

    }

    @Override
    public void onPayWxFailed(String err) {

    }

    @Override
    public void onDetailSuccess(OrderDetailBean orderDetailBean) {

    }

    @Override
    public void onDetailFailed(String err) {

    }

    @Override
    public void onExpressSuccess(ExpressBean expressBean) {

    }

    @Override
    public void onExpressFailed(String err) {

    }

    @OnClick({R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                submit();
                break;
        }
    }

    /**
     * 获取需要上传的图片数组
     *
     * @return
     */
    private List<String> getPicList() {
        List<UploadImageBean> data = uploadImageListAdapter.getData();
        List<String> picList = new ArrayList<>();
        for (UploadImageBean bean : data) {
            if (bean.getItemType() == 0) {
                picList.add(bean.getPath());
            }
        }
        return picList;
    }

    /**
     * 提交
     */
    private void submit() {
        if (etMsg.getText().toString().length() == 0) {
            switch (type) {
                case 1://退款
                    ToastUtils.showShort("请输入退款原因");
                    break;
                case 2://换货
                    ToastUtils.showShort("请输入换货原因");
                    break;
            }
            return;
        }
        List<String> picList = getPicList();
        showLoadingDialog();
        if (picList.size() > 0) {
            //上传图片
            picUrlList.clear();
            uploadImages(picList);
            return;
        }
        submit(picList);
    }

    private void submit(List<String> picList) {
        String picArrayStr = JSON.toJSONString(picList);
        OrderModel.refund(getIntent().getStringExtra("orderId"), type, etMsg.getText().toString(), picArrayStr, "STORE", new ApiModel.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                hideLoadingDialog();
                EventBus.getDefault().post(new EventOrderMsg(3));
                EventBus.getDefault().post(new EventOrderMsg(4));
                ToastUtils.showShort(s);
                finish();
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);

//                    File file = new File(images.get(0).getPath());
//                    Log.e("图片上传", "file:" + images.get(0).getPath());
//                    upload(file);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }

    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {

        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        List<File> fileList = new ArrayList<>();
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
            fileList.add(new File(localMedia.getCompressPath()));
        }
        List<UploadImageBean> temp = uploadImageListAdapter.getData();
        temp.remove(temp.size() - 1);
        temp.addAll(data);
        temp.add(new UploadImageBean());
        uploadImageListAdapter.setNewData(temp);

        if (uploadImageListAdapter.getData().size() == 7) {
            uploadImageListAdapter.getData().remove(6);
        }
        uploadImageListAdapter.notifyDataSetChanged();
    }

    /**
     * 上传多张图片
     */
    private void uploadImages(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            upload(i, new File(list.get(i)));
        }
    }

    List<String> picUrlList = new ArrayList<>();

    private void finishLoad(int position, String url, boolean success) {
        picUrlList.add(url);
        if (picUrlList.size() == getPicList().size()) {
            submit(picUrlList);
        }
    }

    /**
     * 上传图片
     *
     * @param position
     * @param file
     */
    private RequestBody upload(int position, File file) {
        //参数添加
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        //构造参数
        RequestBody body = builder.build();

        //上传
        OrderModel.uploadImage(body, new ApiModel.CommonCallback<UploadImageResultBean>() {
            @Override
            public void onSuccess(UploadImageResultBean uploadImageResultBean) {
                finishLoad(position, uploadImageResultBean.getUrl(), true);
            }

            @Override
            public void onError(String errMsg) {
                ToastUtils.showShort(errMsg);
                finishLoad(position, "", true);
            }
        });
        return body;
    }

    /**
     * 打开图片选择器
     */
    private void selectImages() {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(7 - uploadImageListAdapter.getData().size())//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
}
